package com.example.register;

import com.example.register.service.ServerService;
import com.example.registerapi.RegisterInfo;
import com.example.registerapi.RegisterInfoHolder;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author：kangxuan
 * @date：2024/9/30 9:33 AM
 * @desc:
 */
@RestController
public class RegisterController  {

    @Autowired
    private ServerService  serverService;


    /**
     * 服务注册
     * @return
     */
    @GetMapping("/register")
    public String register(String name,String port,HttpServletRequest request){
        String remoteAddr = request.getRemoteAddr();
        String ip = remoteAddr.contains("0:0:0:0:0:0")?"127.0.0.1":remoteAddr;
        RegisterInfoHolder.register(name,ip,port);

        // 异步通知所有服务
        serverService.publishEvent(name,port,ip,EventType.REGISTER);
        return "register";
    }



    @GetMapping("/observer")
    public Object observer(String name,String port,HttpServletRequest request){
        String remoteAddr = request.getRemoteAddr();
        RegisterInfoHolder.addListener(new RegisterInfo(name,remoteAddr.contains("0:0:0:0:0:0")?"127.0.0.1":remoteAddr,port));

        return RegisterInfoHolder.getAllRegisterInfos();
    }

    /**
     * 服务注销
     * @return
     */
    @GetMapping("/logout")
    public String logout(String name,String port,HttpServletRequest request){
        String remoteAddr = request.getRemoteAddr();
        RegisterInfoHolder.remove(name,remoteAddr.contains("0:0:0:0:0:0")?"127.0.0.1":remoteAddr,port);

        // todo 通知所有服务
        return "logout";
    }

    /**
     * 服务发现
     * @return
     */
    @GetMapping("/find")
    public Object login(String name){
        return RegisterInfoHolder.getRegisterInfos(name);
    }

}
